# This file is part of the Lumenn project 
# at http://code.google.com/p/lumenn/
#
# Released under the GPLv3 at http://www.gnu.org/copyleft/gpl.html
# Designed for pygtk and the Maemo platform.
#
# Copyright 2008 by Jackson Yee (jackson@gotpossum.com)

import pickle
import os
import os.path
import sys
import time
from lumenn.files import MkDir
from lumenn.log import log

# *********************************************************************
class Config(object):
	
	# -------------------------------------------------------------------
	def __init__(self, appname):
		self.appname = appname
		self.data = {}
		
		if os.name == 'posix':
			self.dirname = os.path.join(os.environ['HOME'],
				'.config',
				appname)
		elif os.name == 'nt':
			self.dirname = os.path.join(os.environ['HOMEPATH'],
				'.config',
				appname)
		
		try:
			MkDir(self.dirname)
		except EnvironmentError, e:
			if e.errno != 17:
				log.write(e)
		
		self.filename = os.path.join(self.dirname, 'settings')
	
	# -------------------------------------------------------------------
	def GetFileName(self, filename):
		return os.path.join(self.dirname, filename)
		
	# -------------------------------------------------------------------
	def Load(self):
		try:
			f = file(self.filename, 'rb')			
			self.data = pickle.load(f)
			f.close()
		except EnvironmentError, e:
			log.write('Config: could not load settings: %s' % e)
		
	# -------------------------------------------------------------------
	def Save(self):
		f = file(self.filename, 'wb')
		pickle.dump(self.data, f, pickle.HIGHEST_PROTOCOL)
		f.close()
		
	# -------------------------------------------------------------------
	def __getitem__(self, k):
		return self.data[k]
	
	# -------------------------------------------------------------------
	def __setitem__(self, k, v):
		self.data[k] = v
	
	# -------------------------------------------------------------------
	def __delitem__(self, k):
		del self.data[k]
		
	# -------------------------------------------------------------------
	def get(self, k, default = None):
		if self.data.has_key(k):
			return self.data[k]
		
		return default

